package com.heima.wemedia.service.impl;

import com.heima.apis.article.ApArticleClient;
import com.heima.model.article.pojos.ApArticle;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.dtos.WmNewsPageDto;
import com.heima.utils.thread.WmThreadLocalUtils;
import com.heima.wemedia.service.WmStatisticsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
public class WmStatisticsServiceImpl implements WmStatisticsService {

    @Autowired
    private ApArticleClient apArticleClient;

    /**
     * 统计
     * @param beginDate
     * @param endDate
     * @return
     */
    @Override
    public ResponseResult newsDimension(Date beginDate, Date endDate) {
        //参数校验
        if (beginDate==null || endDate==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //处理为当天的日期
        endDate=new Date(endDate.getTime()+1000*60*60*24-1);
        //作者id
        Integer wmUserId = WmThreadLocalUtils.getUser().getId();
        //获取作者的文章
        List<ApArticle> apArticleList= apArticleClient.getAllArticle(beginDate,endDate,wmUserId);
        //获取点赞总数 未去除 null值
        //int likesNum = apArticleList.stream().mapToInt(ApArticle::getLikes).reduce(0, Integer::sum);
        //int likesNum = apArticleList.stream().mapToInt(ApArticle::getLikes).sum();

        // 去除 null值求和
        int likesNum = apArticleList.stream().filter(apArticle -> apArticle.getLikes()!=null).mapToInt(ApArticle::getLikes).sum();
        //将 null 值替换成 0 求和
        //int likesNum = apArticleList.stream().mapToInt(apArticle -> apArticle.getLikes()==null? 0 :apArticle.getLikes()).sum();

        //获取收藏总数 去除 null值求和
        //int collectNum = apArticleList.stream().mapToInt(ApArticle::getCollection).reduce(0, Integer::sum);
        int collectNum = apArticleList.stream().filter(apArticle -> apArticle.getCollection()!=null).mapToInt(ApArticle::getCollection).sum();
        //发布数量
        int publishNum = apArticleList.size();
        Map<String,Object> map=new HashMap<>();
        map.put("likesNum",likesNum);
        map.put("collectNum",collectNum);
        map.put("publishNum",publishNum);

        return ResponseResult.okResult(map);
    }


    /**
     * 分页展示
     * @param dto
     * @return
     */
    @Override
    public ResponseResult newsPage(WmNewsPageDto dto) {
        //校验参数
        //参数校验
        if (dto.getBeginDate()==null || dto.getEndDate()==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //作者id
        Integer wmUserId = WmThreadLocalUtils.getUser().getId();

        return apArticleClient.getNewsPage(dto,wmUserId);

    }
}
